/*
 *  ETLoop.cpp
 *  EidoTron
 *
 *  Created by Luca Di Franco on 07/03/11.
 *  Copyright 2011 Luca Di Franco. All rights reserved.
 *
 */

#include "EidoTronApp.h"

#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <vector>

#include "../Scene_organization/CollisionManager.h"
#include "../Scene_organization/SceneNode.h"
#include "../Entities/Battleground.h"
#include "../Entities/Lightcycle.h"
#include "../Utilities/Timer.h"


using std::max;
using std::min;
using std::pair;
using std::vector;


void EidoTronApp::loop()
{	
	float lapTime = Timer::getLastLap();
	
	// Player
	greenCycle->memMove(((Lightcycle*)greenCycle->data)->getCurrentSpeed() * lapTime);
	
	// CPU
	redCycle->memMove(((Lightcycle*)redCycle->data)->getCurrentSpeed() * lapTime);
	redCycle->memRotate(((Lightcycle*)redCycle->data)->getAgility() * Timer::getLastLap(), 0.0f, 1.0f, 0.0f);
	blueCycle->memMove(((Lightcycle*)blueCycle->data)->getCurrentSpeed() * lapTime);
	blueCycle->memRotate(-((Lightcycle*)blueCycle->data)->getAgility() * Timer::getLastLap(), 0.0f, 1.0f, 0.0f);
	
	// Collisions
	vector< pair< SceneNode*, SceneNode* > >* collisions = CollisionManager::getCollisions();
	for (vector< pair< SceneNode*, SceneNode* > >::iterator iter = collisions->begin(); iter != collisions->end(); iter++)
	{
		if ((*iter).first != SceneNode::getPlayerNode())
		{
			float newX = (float) max(rand() % (((Battleground*)(battleground->data))->size_x - 2) * 5, 20);
			float newZ = (float) max(rand() % (((Battleground*)(battleground->data))->size_z - 2) * 5, 20);
			(*iter).first->setTranslate(newX, 0.0f, -newZ);
		}	
		if ((*iter).second != SceneNode::getPlayerNode())
		{
			float newX = (float) max(rand() % (((Battleground*)(battleground->data))->size_x - 2) * 5, 20);
			float newZ = (float) max(rand() % (((Battleground*)(battleground->data))->size_z - 2) * 5, 20);
			(*iter).second->setTranslate(newX, 0.0f, -newZ);
		}
	}
}